package com.puzzlebazar.client.puzzle.view;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DeferredCommand;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;

public class MessageDialog extends DialogBox {

	public interface Callback {
		/**
		 * Callback used when OK is pressed
		 * 
		 * @param message The message entered in the dialog box
		 */
		public void ok( String message );
		/**
		 * Callback used when CANCEL is pressed
		 */
		public void cancel();
	}
	
	final TextBox messageText = new TextBox();

	public MessageDialog( final Callback callback ) throws Exception {
	
		// Set the dialog box's caption.
		setText("Enter message");

		final VerticalPanel mainPanel = new VerticalPanel();
		mainPanel.setWidth( "100%" );

		final HorizontalPanel subPanel = new HorizontalPanel();
		subPanel.setWidth( "100%" );
		
		final Label messageLabel  = new Label( "Message :" );	      
		messageLabel.setWidth( "90px" );
		messageText.setWidth("400px");		

		subPanel.add( messageLabel );
		subPanel.add( messageText );
		
		final HorizontalPanel buttonPanel = new HorizontalPanel();

		final Button ok = new Button("OK");
		ok.setWidth( "75px" );
		ok.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				callback.ok( messageText.getText() );
				MessageDialog.this.hide();
			}
		});
		
		final Button cancel = new Button("Cancel");
		cancel.setWidth( "75px" );
		cancel.addClickHandler(new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				callback.cancel();
				MessageDialog.this.hide();
			}
		});
		
		buttonPanel.add( ok );
		buttonPanel.setCellWidth( ok, "80px" );
		buttonPanel.add( cancel );
		buttonPanel.setCellWidth( cancel, "80px" );
		
		mainPanel.add( subPanel );
		mainPanel.add( buttonPanel );
		setWidget(mainPanel);
		setModal(true);

		setAnimationEnabled(true);

		DeferredCommand.addCommand( new Command() {
			@Override
			public void execute() {
				messageText.setFocus( true );
				messageText.selectAll();
			}			
		});
		
	}

	/**
	 * Sets the message to display in the edit field
	 * 
	 * @param message The message to display
	 */
	public void setMessage(String message) {
		messageText.setText(message);
	}
}
